package com.l024.meet.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.l024.framework.adapter.CommonAdapter;
import com.l024.framework.adapter.CommonViewHolder;
import com.l024.framework.base.BaseUIActivity;
import com.l024.framework.bmob.BmobManager;
import com.l024.framework.bmob.Friend;
import com.l024.framework.bmob.IMUser;
import com.l024.framework.cloud.CloudManager;
import com.l024.framework.entity.Constants;
import com.l024.framework.helper.GlideHelper;
import com.l024.framework.manager.DialogManager;
import com.l024.framework.utils.CommonUtils;
import com.l024.framework.utils.Logutils;
import com.l024.framework.view.DialogView;
import com.l024.meet.R;
import com.l024.meet.model.UserInfoModel;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 用戶信息界面
 */
public class UserInfoActivity extends BaseUIActivity implements View.OnClickListener {

    /**
     * 1.根据传递的用户id查询用户信息
     * -1.普通信息
     * -2.构建一个RecyclerView 宫格
     * 2.建立好友关系模型
     *  1.在我好友列表
     *  2.同意了我好友申请
     *  3.查询我所有的好友列表，
     * 3.实现添加好友
     * 4.发送添加好友
     *  1.自定义消息类型
     *  2.自定义协议
     *  发送文本消息，COntent 可以发送json消息
     * 5.接受好友信息
     */
    private RelativeLayout llBack;
    private CircleImageView ivUserPhoto;
    private TextView tvNickname;
    private TextView tvDesc;
    private RecyclerView mUserInfoView;
    private Button btnAddFriend;
    private LinearLayout llIsFriend;
    private Button btnChat;
    private Button btnAudioChat;
    private Button btnVideoChat;

    //获取用户id
    String userId = "";
    //个人信息颜色
    private int[] mColor = {0x881E90FF, 0x8800FF7F, 0x88FFD700, 0x88FF6347, 0x88F08080, 0x8840E0D0};

    //适配器
    private CommonAdapter<UserInfoModel> mUserInfoAdapter;
    private List<UserInfoModel> userInfoModels = new ArrayList<>();
    private EditText etMsg;
    private TextView tvCancel;
    private TextView tvAddFriend;

    DialogView mAddFriendDialogView = null;

    /**
     * 跳转
     *
     * @param
     */
    public static void startActivity(Context context, String userId) {
        Intent intent = new Intent(context, UserInfoActivity.class);
        intent.putExtra(Constants.INTENT_USER_ID, userId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            userId = extras.getString(Constants.INTENT_USER_ID);
            queryUserById();
        }
        llBack = (RelativeLayout) findViewById(R.id.ll_back);
        ivUserPhoto = (CircleImageView) findViewById(R.id.iv_user_photo);
        tvNickname = (TextView) findViewById(R.id.tv_nickname);
        tvDesc = (TextView) findViewById(R.id.tv_desc);
        mUserInfoView = (RecyclerView) findViewById(R.id.mUserInfoView);
        btnAddFriend = (Button) findViewById(R.id.btn_add_friend);
        llIsFriend = (LinearLayout) findViewById(R.id.ll_is_friend);
        btnChat = (Button) findViewById(R.id.btn_chat);
        btnAudioChat = (Button) findViewById(R.id.btn_audio_chat);
        btnVideoChat = (Button) findViewById(R.id.btn_video_chat);

        btnAddFriend.setOnClickListener(this);
        btnAudioChat.setOnClickListener(this);
        btnVideoChat.setOnClickListener(this);
        btnChat.setOnClickListener(this);
        llBack.setOnClickListener(this);

        //设置用户资料显示
        mUserInfoAdapter = new CommonAdapter<UserInfoModel>(userInfoModels, new CommonAdapter.OnBindDataListener<UserInfoModel>() {
            @Override
            public void onBindViewHolder(UserInfoModel model, CommonViewHolder commonViewHolder, int type, int position) {
                commonViewHolder.setText(R.id.tv_type, model.getTitle());
                commonViewHolder.setText(R.id.tv_content, model.getContent());
                commonViewHolder.getView(R.id.ll_bg).setBackgroundColor(model.getBgColor());
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_user_info_item;
            }
        });
        mUserInfoView.setLayoutManager(new GridLayoutManager(this, 3));
        mUserInfoView.setAdapter(mUserInfoAdapter);

        //初始化添加好友弹窗
        initAddFriendDialog();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //添加好友
            case R.id.btn_add_friend:{
                DialogManager.getInstance().show(mAddFriendDialogView);
                break;
            }
            //返回
            case R.id.iv_back:{
                finish();
                break;
            }
            //添加好友
            case R.id.tv_add_friend:{
                String msg = etMsg.getText().toString().trim();
                if(TextUtils.isEmpty(msg)){
                    msg = "你好，我是"+BmobManager.getInstance().getUser().getNickName();
                }
                //发送消息
                CloudManager.getInstance().sendAddFrientMessage(msg,CloudManager.TYPE_ADD_FRIEND,userId);
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
                DialogManager.getInstance().hide(mAddFriendDialogView);
                break;
            }
            //取消
            case R.id.tv_cancel:{
                DialogManager.getInstance().hide(mAddFriendDialogView);
                break;
            }
        }
    }

    /**
     * 查询用户信息
     */
    private void queryUserById() {
        if (!TextUtils.isEmpty(userId)) {
            BmobManager.getInstance().queryObjectIdFriend(userId, new FindListener<IMUser>() {
                @Override
                public void done(List<IMUser> list, BmobException e) {
                    if (e == null) {
                        if (CommonUtils.isEmpty(list)) {
                            IMUser imUser = list.get(0);
                            updateUserInfo(imUser);
                        }
                    } else {
                        Logutils.e("查询用户失败：userid:" + userId + "  错误信息:" + e);
                    }
                }
            });
        } else {
            Toast.makeText(this, "查询用户id为NULL", Toast.LENGTH_SHORT).show();
        }
        //查询我的好友信息
        BmobManager.getInstance().queryMyFriends(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if (e == null) {
                    if (CommonUtils.isEmpty(list)) {
                        for (Friend friend : list) {
                            //判断我好友对象中的userId是否和我目前的userId相同
                            if (friend.getFriendUser().getObjectId().equals(userId)) {
                                //是好友关系
                                btnAddFriend.setVisibility(View.GONE);
                                llIsFriend.setVisibility(View.VISIBLE);
                                break;
                            }
                        }
                    } else {
                        Logutils.e("没有好友，非好友关系");
                        btnAddFriend.setVisibility(View.VISIBLE);
                        llIsFriend.setVisibility(View.GONE);
                    }
                } else {
                    Logutils.e("查询我的好友失败");
                }
            }
        });
    }

    /**
     * 添加好友dialog
     */
    private void initAddFriendDialog() {
        mAddFriendDialogView = DialogManager.getInstance().initView(this, R.layout.dialog_send_friend);
        etMsg = (EditText) mAddFriendDialogView.findViewById(R.id.et_msg);
        tvCancel = (TextView) mAddFriendDialogView.findViewById(R.id.tv_cancel);
        tvAddFriend = (TextView) mAddFriendDialogView.findViewById(R.id.tv_add_friend);

        tvCancel.setOnClickListener(this);
        tvAddFriend.setOnClickListener(this);
    }

    //设置用户信息
    private void updateUserInfo(IMUser imUser) {
        //设置用户信息
        //设置头像
        GlideHelper.loadUrl(UserInfoActivity.this, imUser.getPhoto(), ivUserPhoto);
        //网名
        tvNickname.setText(imUser.getNickName());
        //描述
        tvDesc.setText(imUser.getDesc());
        //构建RecyclerView
        //性别，年龄 生日 爱好 星座 爱好 单身状态
        addUserInfoModel(mColor[0], getString(R.string.text_me_info_sex), imUser.isSex() ? getString(R.string.text_me_info_boy) : getString(R.string.text_me_info_girl));
        addUserInfoModel(mColor[1], getString(R.string.text_me_info_age), imUser.getAge() + getString(R.string.text_search_age));
        addUserInfoModel(mColor[2], getString(R.string.text_me_info_birthday), imUser.getBitrhDay());
        addUserInfoModel(mColor[3], getString(R.string.text_me_info_constellation), imUser.getConstellation());
        addUserInfoModel(mColor[4], getString(R.string.text_me_info_hobby), imUser.getHobby());
        addUserInfoModel(mColor[5], getString(R.string.text_me_info_status), imUser.getStatus());
        //刷新数据
        mUserInfoAdapter.notifyDataSetChanged();
    }

    private void addUserInfoModel(int color, String title, String content) {
        UserInfoModel userInfoModel = new UserInfoModel();
        userInfoModel.setBgColor(color);
        userInfoModel.setTitle(title);
        userInfoModel.setContent(content);
        userInfoModels.add(userInfoModel);
    }
}
